<template>
  <div style="padding: 20px">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
      <el-form-item label="店铺" prop="shopId">
        <el-select v-model="queryParams.storeId" filterable clearable @keyup.enter.native="handleQuery"
                   @change="clearStoreId()" placeholder="请选择店铺">
          <el-option v-for="item in storeMgmtList" :key="item.id" :label="item.storeAbbr" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="事业部" prop="divName">
        <el-select v-model="queryParams.divName" collapse-tags filterable clearable @keyup.enter.native="handleQuery"
                   @change="clearDivName()" placeholder="请选择事业部">
          <el-option v-for="item in divNameOptions" :key="item.value" :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品标签" prop="shopId">
        <el-input placeholder="请输入商品标签" v-model="queryParams.goodsLabel" @keyup.enter.native="handleQuery"
                  @change="clearGoodsLabel()" clearable style="float: left;width: calc(100% - 35px);"></el-input>
      </el-form-item>
      <el-form-item label="负责人" prop="storeLeader">
        <el-select v-model="queryParams.storeLeader" clearable @keyup.enter.native="handleQuery"
                   @change="clearStoreLeader()" placeholder="请选择负责人">
          <el-option v-for="item in leaderList" :key="item.userId" :label="item.nickName" :value="item.userId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上新日期" prop="upNewDate">
        <el-date-picker
          type="months"
          v-model="queryParams.upNewDateList"
          placeholder="选择一个或多个月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="统计日期" prop="statDate">
        <el-date-picker
          type="months"
          v-model="queryParams.monthList"
          placeholder="选择一个或多个月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button icon="el-icon-download" @click="handleExport">下载</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="toolbar">
      <el-col :span="24">
        <el-table :data="tableData" height="300" style="width: 100%" v-loading="loading">
          <el-table-column prop="statDate" label="日期"></el-table-column>
          <el-table-column prop="count_500_plus" label="500以上">
            <template slot-scope="scope">
              <div @click="clickSkip(scope.column.label, scope.row.statDate)">
                {{ scope.row.count_500_plus ? scope.row.count_500_plus : 0 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="count_200_500" label="200-500">
            <template slot-scope="scope">
              <div @click="clickSkip(scope.column.label, scope.row.statDate)">
                {{ scope.row.count_200_500 ? scope.row.count_200_500 : 0 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="count_100_200" label="100-200">
            <template slot-scope="scope">
              <div @click="clickSkip(scope.column.label, scope.row.statDate)">
                {{ scope.row.count_100_200 ? scope.row.count_100_200 : 0 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="count_50_100" label="50-100">
            <template slot-scope="scope">
              <div @click="clickSkip(scope.column.label, scope.row.statDate)">
                {{ scope.row.count_50_100 ? scope.row.count_50_100 : 0 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="count_30_50" label="30-50">
            <template slot-scope="scope">
              <div @click="clickSkip(scope.column.label, scope.row.statDate)">
                {{ scope.row.count_30_50 ? scope.row.count_30_50 : 0 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="count_10_30" label="10-30">
            <template slot-scope="scope">
              <div @click="clickSkip(scope.column.label, scope.row.statDate)">
                {{ scope.row.count_10_30 ? scope.row.count_10_30 : 0 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="count_3_10" label="3-10">
            <template slot-scope="scope">
              <div @click="clickSkip(scope.column.label, scope.row.statDate)">
                {{ scope.row.count_3_10 ? scope.row.count_3_10 : 0 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="count_1_3" label="1-3">
            <template slot-scope="scope">
              <div @click="clickSkip(scope.column.label, scope.row.statDate)">
                {{ scope.row.count_1_3 ? scope.row.count_1_3 : 0 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="count_0" label="0">
            <template slot-scope="scope">
              <div @click="clickSkip(scope.column.label, scope.row.statDate)">
                {{ scope.row.count_0 ? scope.row.count_0 : 0 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="count_all" label="合计"></el-table-column>
          <el-table-column prop="salesTurnoverRate" label="动销率">
            <template slot-scope="scope">
              {{ scope.row.salesTurnoverRate ? scope.row.salesTurnoverRate : 0 }}%
            </template>
          </el-table-column>
          <el-table-column prop="salesTurnoverRateThree" label="动销率3">
            <template slot-scope="scope">
              {{ scope.row.salesTurnoverRateThree ? scope.row.salesTurnoverRateThree : 0 }}%
            </template>
          </el-table-column>
          <el-table-column prop="netSalesRevenue" label="净销售额">
            <template slot-scope="scope">
              {{ divideAndFormat(scope.row.netSalesRevenue) }}万
            </template>
          </el-table-column>
          <el-table-column prop="promotionRatio" label="推广占比">
            <template slot-scope="scope">
              {{ scope.row.promotionRatio ? scope.row.promotionRatio : 0 }}%
            </template>
          </el-table-column>
          <el-table-column prop="customerOrderPrice" label="客单价">
            <template slot-scope="scope">
              {{ scope.row.customerOrderPrice ? scope.row.customerOrderPrice : 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="dynamicSalesThree" label="动销3价值">
            <template slot-scope="scope">
              {{ scope.row.dynamicSalesThree ? scope.row.dynamicSalesThree : 0 }}
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="24">
        <div id="productTierDashboard" style="width: 100%;height: 380px;margin: 10px auto;"></div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {generateColors, line_bar_chart} from "@/utils/echartsOption";
import {getNormalStoreMgmtList, getProductMonthEchelon, getStoreLeaderList} from "@/api/business/storeMgmt"
import {parseTime} from "@/utils/basic";
import {exportProductDateEchelon} from "@/api/business/goodsIndicators";

export default {
  name: "ProductTierDashboardTime",
  components: {},
  data() {
    return {
      productTierDashboard: null,
      tableData: [],
      storeMgmtList: [],
      queryParams: {
        storeId: null,
        divName: null,
        goodsLabel: null,
        storeLeader: null,
        upNewDateList: [],
        monthList: [],
      },
      divNameOptions: [{
        value: '海报事业部',
        label: '海报事业部'
      }, {
        value: '3C事业部',
        label: '3C事业部'
      }],
      loading: false,
      leaderList:[]
    }
  },
  created() {
    this.getNormalStoreMgmtList();
    this.getStoreLeaderList();
  },
  mounted() {
    this.productTierDashboard = echarts.init(document.getElementById('productTierDashboard'))
    window.addEventListener('resize', () => {
      this.productTierDashboard.resize()
    })
    this.getProductTierDashboard()
  },
  methods: {
    /** 查询店铺列表 */
    getNormalStoreMgmtList() {
      getNormalStoreMgmtList().then(res => {
        this.storeMgmtList = res.data
      })
    },
    getProductTierDashboard() {
      const _this = this;
      let data = [], xData = ['500以上', '200-500', '100-200', '50-100', '30-50', '10-30', '3-10', '1-3', '0', '合计'],
        legend = [], company = []
      this.tableData.map(i => {
        data.push({
          type: 0,
          fontColor: 'black',
          topLineLabel: 'top',
          data: [i.count_500_plus, i.count_200_500, i.count_100_200, i.count_50_100, i.count_30_50, i.count_10_30, i.count_3_10, i.count_1_3, i.count_0, i.count_all],
          topLine: true,
          name: i.store_name ? i.store_name : i.goodsLabel ? i.goodsLabel : i.store_leader
        })
        legend.push(i.statDate)
        company.push('')
      })
      _this.productTierDashboard.clear();
      const option = line_bar_chart({
        legend: legend,
        xData: xData,
        data: data,
        company: company,
        color: generateColors(legend.length),
        type: 1,
        grid: ["50px", "7%", "0%", "4px"],
        dataZoom: xData.length > 12,
        barWidth: '12px',
        fontColor: 'black',
        titleColor: 'black'
      })
      _this.productTierDashboard.setOption(option);
    },
    handleQuery() {
      let queryParams = JSON.parse(JSON.stringify(this.queryParams));
      if (!queryParams.storeId && !queryParams.goodsLabel && !queryParams.storeLeader && !queryParams.divName) {
        this.$message.error('请选择店铺/事业部/商品标签/负责人！！！！');
        return false
      }
      if (queryParams.monthList.length === 0) {
        this.$message.error('请选择统计日期！！！！');
        return false
      }
      this.loading = true
      queryParams.monthList.map((item, index) => {
        queryParams.monthList[index] = parseTime(item, '{y}-{m}')
      })

      if (queryParams.upNewDateList.length > 0) {
        queryParams.upNewDateList.map((item, index) => {
          queryParams.upNewDateList[index] = parseTime(item, '{y}-{m}')
        })
      }

      getProductMonthEchelon(queryParams).then(res => {
        this.tableData = res.data
        this.getProductTierDashboard()
        this.loading = false
      })
    },
    clearStoreId() {
      this.queryParams.storeLeader = null
      this.queryParams.goodsLabel = null
      this.queryParams.divName = null
    },
    clearStoreLeader() {
      this.queryParams.storeId = null
      this.queryParams.goodsLabel = null
      this.queryParams.divName = null
    },
    clearGoodsLabel() {
      this.queryParams.storeId = null
      this.queryParams.storeLeader = null
      this.queryParams.divName = null
    },
    clearDivName() {
      this.queryParams.storeId = null
      this.queryParams.storeLeader = null
      this.queryParams.goodsLabel = null
    },
    resetQuery() {
      this.queryParams = {
        storeId: null,
        divName: null,
        goodsLabel: null,
        storeLeader: null,
        upNewDateList: [],
        monthList: [],
      }
      this.$resetForm("queryParams");
      this.productTierDashboard.clear();
      this.tableData = []
    },
    divideAndFormat(number) {
      if (number) {
        // 将数字除以10000
        let result = number / 10000;
        // 使用toFixed方法保留1位小数
        result = result.toFixed(2);
        // 将结果转换回数字（如果需要）
        // 注意：toFixed返回的是一个字符串，如果需要数字类型，可以使用parseFloat或Number
        result = parseFloat(result);
        return result;
      } else {
        return 0
      }
    },
    // 跳转商品指标页面
    clickSkip(label, statDate) {
      //统计日期使用集合范围值，商品指标页面查询时有处理
      let query = {
        statDateRange: this.getStatDateRange(statDate)
      }
      //店铺 事业部 商品标签 负责人 四选一
      if (this.queryParams.storeId) {
        query.storeId = this.queryParams.storeId
      }
      if (this.queryParams.divName) {
        query.divName = this.queryParams.divName
      }
      if (this.queryParams.goodsLabel) {
        query.goodsLabel = this.queryParams.goodsLabel
      }
      if (this.queryParams.storeLeader) {
        query.storeLeader = this.queryParams.storeLeader
      }
      //上新日期
      if (this.queryParams.upNewDateList.length > 0) {
        query.upNewDateStart = this.getUpNewDateRange(this.queryParams.upNewDateList).startDate
        query.upNewDateEnd = this.getUpNewDateRange(this.queryParams.upNewDateList).endDate
      }
      //支付买家数
      if (label === '500以上') {
        query.payBuyerNumberMin = 500
      }
      if (label === '0') {
        query.payBuyerNumberMin = 0
      }
      if (label !== '500以上' && label !== '0') {
        query.payBuyerNumberMin = this.getPayBuyerNumberRange(label).min
        query.payBuyerNumberMax = this.getPayBuyerNumberRange(label).max
      }

      this.$router.push({
        path: '/operation/goodsIndicators', // 目标路由路径
        query: query, // 参数对象
      });
    },
    //获取上新日期范围值
    getUpNewDateRange(yearMonths) {
      if (!yearMonths || yearMonths.length === 0) {
        return {startDate: null, endDate: null};
      }

      // 1. 解析所有年月并转换为日期对象
      const dates = yearMonths.map(ym => {
        const [year, month] = ym.split('-').map(Number);
        // 创建当月第一天的日期对象（时间设为0时0分0秒）
        return new Date(year, month - 1, 1);
      });

      // 2. 找出最小和最大日期
      const minDate = new Date(Math.min(...dates.map(d => d.getTime())));
      const maxDate = new Date(Math.max(...dates.map(d => {
        // 最大日期需要计算当月的最后一天
        return new Date(d.getFullYear(), d.getMonth() + 1, 0);
      })));

      // 3. 格式化日期为 YYYY-MM-DD
      const formatDate = (date) => {
        if (!date) return null;
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };

      return {
        startDate: formatDate(minDate), // 集合中最早月份的第一天
        endDate: formatDate(maxDate)    // 集合中最晚月份的最后一天
      };
    },
    //获取支付买家数范围值
    getPayBuyerNumberRange(label) {
      // 分割字符串
      const parts = label.split('-');

      // 检查分割后的数组长度是否为2
      if (parts.length !== 2) {
        throw new Error('输入格式不正确，应为 "min-max" 格式');
      }

      // 将字符串转换为数字
      const min = parseFloat(parts[0]);
      const max = parseFloat(parts[1]);

      // 检查转换结果是否为有效数字
      if (isNaN(min) || isNaN(max)) {
        throw new Error('范围值必须是有效数字');
      }

      // 返回结果对象
      return {min, max};
    },
    // 获取统计时间范围
    getStatDateRange(yearMonth) {
      const [year, month] = yearMonth.split('-').map(Number);

      // 计算第一天（直接设为1号）
      const firstDay = new Date(year, month - 1, 1); // 月份是0-based

      // 计算最后一天（下个月的第0天）
      const lastDay = new Date(year, month, 0);

      // 格式化日期为 'YYYY-MM-DD'
      const formatDate = (date) => {
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0'); // 补零
        const d = String(date.getDate()).padStart(2, '0');     // 补零
        return `${y}-${m}-${d}`;
      };

      return [formatDate(firstDay), formatDate(lastDay)]
    },
    // 导出
    handleExport() {

      if (this.tableData.length === 0) {
        this.$message.warning('请先查询后下载');
        return false
      }

      let queryParams = JSON.parse(JSON.stringify(this.queryParams));
      if (!queryParams.storeId && !queryParams.goodsLabel && !queryParams.storeLeader && !queryParams.divName) {
        this.$message.error('请选择店铺/事业部/商品标签/负责人！！！！');
        return false
      }
      if (queryParams.monthList.length === 0) {
        this.$message.error('请选择统计日期！！！！');
        return false
      }

      queryParams.monthList.map((item, index) => {
        queryParams.monthList[index] = parseTime(item, '{y}-{m}')
      })

      if (queryParams.upNewDateList.length > 0) {
        queryParams.upNewDateList.map((item, index) => {
          queryParams.upNewDateList[index] = parseTime(item, '{y}-{m}')
        })
      }

      exportProductDateEchelon(queryParams)
    },
    /** 查询店铺负责人列表 */
    getStoreLeaderList(){
      getStoreLeaderList().then(res => {
        this.leaderList = res.data
      })
    },
  }
}
</script>

<style scoped>

</style>
